/**
* @CopyRight xinweitech.cn
* @author wuyahui
* @E-mail wuyahui0124505@163.com
* @version 1.0.0
* @Date  2015年4月3日 下午1:03:40
*/
package com.tstudy.laoshibang.profile;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ViewById;
import org.apache.http.Header;

import com.tstudy.laoshibang.R;
import com.tstudy.laoshibang.base.BaseActivity;
import com.tstudy.laoshibang.base.BaseApplication;
import com.tstudy.laoshibang.base.BaseFragment;
import com.tstudy.laoshibang.base.CONSTANT;
import com.tstudy.laoshibang.base.HttpManager;
import com.tstudy.laoshibang.mode.Message;
import com.tstudy.laoshibang.mode.response.BaseResponse;
import com.tstudy.laoshibang.utils.CommonUtil;
import com.tstudy.laoshibang.utils.LogUtil;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.JsResult;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebSettings.PluginState;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.RelativeLayout;
@SuppressWarnings("deprecation")
@EFragment(R.layout.message_detail)
public class MessageDetailFragment extends BaseFragment{
	final static String TAG = "message_detail";
	public MessageDetailFragment() {
		super();
	}
	
	@ViewById(R.id.message_detail_root)
	RelativeLayout mRootLayout;
	
	@ViewById(R.id.message_detail_webview)
	WebView mWebView;
	
	Message mMessage;
	
	@ViewById(R.id.message_detail_progress)
	RelativeLayout mProgressLayout;
	
	
	String mUrl;
	int mSysMId;
	int position;
	boolean mIsFirstLoad = true;
	Handler mHandler;
	LayoutInflater mInflater;
	String mGroupId;

	public static void add(int containerViewId,int sysMId,int position,String url,ReadCallBack callBack) {
		add(containerViewId, sysMId, position, url,null,callBack);
	}
	public static void add(int containerViewId,int sysMId,int position,String url,String groupId,ReadCallBack callBack) {
		Bundle args = new Bundle();
		args.putInt(CONSTANT.ARGS.FRAGMENT_ID, containerViewId);
		args.putInt(CONSTANT.ARGS.MSG_ID, sysMId);
		args.putInt(CONSTANT.ARGS.POSITION, position);
		args.putString(CONSTANT.ARGS.GROUP_ID, groupId);
		args.putString(CONSTANT.ARGS.URL, url);
		Fragment fragment = Fragment.instantiate(BaseApplication.mContext,MessageDetailFragment_.class.getName(),args);
		((MessageDetailFragment)fragment).mReadCallBack = callBack;
		((BaseActivity) BaseApplication.mCurrentActivity).add(containerViewId, fragment, TAG);
	}
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		mHandler = new Handler();
		super.onCreate(savedInstanceState);
	}
	
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		mInflater = inflater;
		super.onCreateView(inflater, container, savedInstanceState);
		LogUtil.d("--mBaseLayout==" + mRootLayout);
		mIsFirstLoad = mRootLayout == null;
		if (mRootLayout != null) {
			((ViewGroup) mRootLayout.getParent()).removeAllViews();
		}
		return mRootLayout;
	}
	
	@AfterViews
	public void initView(){
		if (mIsFirstLoad) {
			mRootLayout.setOnClickListener(null);
			initWebView();
			mWebView.loadUrl(mUrl);
			showProgressBar(mProgressLayout);
			mHandler.postDelayed(new Runnable() {
				@Override
				public void run() {
//					messageDetail();
					messageRead();
				}
			}, CONSTANT.LOAD_DATA_DELAY_TIME);
		}
		
	}
	
	@SuppressLint("SetJavaScriptEnabled")
	private void initWebView() {// 初始化
		mWebView.getSettings().setSupportZoom(true); // Zoom Control on web (You
		// don't need this
		mWebView.getSettings().setJavaScriptEnabled(true);// 可用JS
		mWebView.getSettings().setAllowContentAccess(true);
		mWebView.getSettings().setPluginState(PluginState.ON);
		mWebView.getSettings().setBuiltInZoomControls(true);
		mWebView.getSettings().setLoadsImagesAutomatically(true);
		mWebView.getSettings().setAllowFileAccess(true);
		mWebView.getSettings().setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);
		// mWebView.getSettings()
		// .setUserAgentString(
		// "Mozilla/5.0 (Linux; U; Android 2.2.1; zh-cn; MB525 Build/3.4.2-117) AppleWebKit/533.1 (KHTML, like Gecko) Version/4.0 Mobile Safari/533.1");
		mWebView.setScrollBarStyle(0);// 滚动条风格，为0就是不给滚动条留空间，滚动条覆盖在网页上
		mWebView.getSettings().setLoadWithOverviewMode(true);
		// sdk 11以上
		// mWebView.getSettings().setDisplayZoomControls(true);
		mWebView.getSettings().setUseWideViewPort(true);
		mWebView.getSettings().setDatabaseEnabled(true);
		mWebView.getSettings().setDomStorageEnabled(true);
		// mWebView.getSettings().setGeolocationEnabled(true);
		mWebView.getSettings().setAppCacheEnabled(true);
		mWebView.getSettings().setAppCacheMaxSize(10000);
//		mWebView.getSettings().setDefaultTextEncodingName("UTF-8");
		mWebView.setWebChromeClient(new WebChromeClient(){
			@Override
			public void onProgressChanged(WebView view, int newProgress) {
				super.onProgressChanged(view, newProgress);
				if (newProgress >= 100) {
					hideProgressBar(mProgressLayout);
				}
			}
			@Override
			public boolean onJsAlert(WebView view, String url, String message, JsResult result) {
				return super.onJsAlert(view, url, message, result);
			}
			
		});
		mWebView.setWebViewClient(new WebViewClient(){
		      @Override
		      public boolean shouldOverrideUrlLoading(WebView view, String url) {
		        // TODO Auto-generated method stub
		        view.loadUrl(url);
		        return true;
		      }
		      @Override
		    public void onPageFinished(WebView view, String url) {
		    	  hideProgressBar(mProgressLayout);
		    	super.onPageFinished(view, url);
		    }
		    });
	}
	
	@Click({R.id.message_detail_back})
	public void actionClick(View view){
		switch (view.getId()) {
		case R.id.message_detail_back:
			backAction(mFragmentId);
			break;
		default:
			break;
		}
	}
	/**
	 * 消息已读接口
	 */
	private void messageRead(){
		BaseListJsonHandler<BaseResponse> response = new BaseListJsonHandler<BaseResponse>() {
			public void onStart() {
				super.onStart();
			}
			@Override
			public void onSuccess(int statusCode, Header[] headers,
					String rawJsonResponse, BaseResponse response) {
				super.onSuccess(statusCode, headers, rawJsonResponse, response);
				if (CommonUtil.responseSuccess(response)) {
					if (mReadCallBack != null) {
						mReadCallBack.readSuccess(position);
					}
				}
			}
			@Override
			public void onFailure(int statusCode, Header[] headers,
					Throwable throwable, String rawJsonData,
					BaseResponse errorResponse) {
				super.onFailure(statusCode, headers, throwable, rawJsonData, errorResponse);
			}
			@Override
			protected BaseResponse parseResponse(String rawJsonData, boolean isFailure)
					throws Throwable {
				return mGson.fromJson(rawJsonData,BaseResponse.class);
			}
		};
		HttpManager.getInstance().messageRead(BaseApplication.mUserNo, mSysMId,mGroupId,response);
	}
	

	public void afterLoading(){
		mIsLoading = false;
		hideProgressBar(mProgressLayout);
	}

	@Override
	public void clear() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void initArgs(Bundle args) {
		if (args != null) {
			mFragmentId = args.getInt(CONSTANT.ARGS.FRAGMENT_ID);
			mUrl = args.getString(CONSTANT.ARGS.URL);
			mSysMId = args.getInt(CONSTANT.ARGS.MSG_ID);
			position = args.getInt(CONSTANT.ARGS.POSITION);
			mGroupId = args.getString(CONSTANT.ARGS.GROUP_ID);
		}
	}
	
	ReadCallBack mReadCallBack;
	public interface ReadCallBack{
		public void readSuccess(int position);
	}

}
